<template>
    <div class="edu-page-warp">
        <ConditionCard
            shadow="never"
            body-style="padding: 24px 24px 6px 24px;"
            @search="onSubmit"
            @reset="reset('queryForm')"
        >
            <el-form ref="queryForm" :model="queryForm" :label-width="language == 'en' ?false:'90px'" label-position="right">
                <el-row :gutter="24" style="height: 50px;">
                    <el-col v-if="showDepartment" :span="6">
                        <el-form-item :label="$t('culture.cultureScheme.proDept')+':'">
                            <el-select
                                v-model="queryForm.projId"
                                style="width: 100%"
                                @change="handleSearch"
                            >
                                <el-option
                                    v-for="item in options.project"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('label.grade')+':'" prop="grade">
                            <el-date-picker
                                v-model="queryForm.grade"
                                :placeholder="$t('culture.scheme.academicYear')"
                                value-format="yyyy"
                                type="year"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('label.trainingLevel')+':'" prop="trainingLevel">
                            <DictSelect
                                v-model="queryForm.trainingLevel"
                                :data="options.trainingLevel"
                                @change="changeTrainingLevel"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('dic.degreeType') + ':'" filterable prop="degreeType">
                            <el-select
                                v-model="queryForm.degreeType"
                                style="width: 100%"
                                clearable
                                @change="changeFaculty">
                                <el-option
                                    v-for="item in options.degreeType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('label.college')+':'" prop="faculty" >
                            <DictSelect
                                v-model="queryForm.faculty"
                                :data="options.faculty"
                                filterable
                                @change="changeFaculty"
                            />
                        </el-form-item>
                    </el-col>
                    <template>
                        <el-col :span="6">
                            <el-form-item :label="$t('culture.scheme.major')+':'" filterable prop="major">
                                <el-select v-model="queryForm.major" style="width: 100%">
                                    <el-option
                                        v-for="item in options.major"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item :label="$t('culture.scheme.formLearning')+':'" prop="formLearning">
                                <el-select v-model="queryForm.formLearning" style="width: 100%">
                                    <el-option
                                        v-for="item in options.formLearning"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item :label="$t('culture.scheme.trainingCategory')+':'" prop="trainingCategory">
                                <el-select
                                    v-model="queryForm.trainingCategory"
                                    style="width: 100%"
                                    clearable
                                    multiple
                                    collapse-tags>
                                    <el-option
                                        v-for="item in options.trainingCategory"
                                        :key="item.code"
                                        :label="item.name"
                                        :value="item.code"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                </el-row>
            </el-form>
        </ConditionCard>
        <el-card shadow="never" body-style="padding: 24px;" class="card-margin">
            <h1 class="condition-title">{{ $t('message.cultureScheme') }}</h1>
            <div class="div-main clearfix">
                <div class="float-left">
                    <el-input
                        v-model="queryForm.name"
                        :placeholder="$t('culture.profession.searchForScheneName')"
                        prefix-icon="el-icon-search"
                        @change="handSearchChang"
                    />
                </div>
                <div class="float-right">
                    <el-button
                        v-if="role == 4 && false"
                        @click="exportFile('word')"
                    >{{ $t('culture.cultureScheme.exportWordZip') }}</el-button>
                    <el-button
                        @click="exportFile('pdf', 'cn')"
                    >{{ $t('culture.cultureScheme.exportPdf') + ` (${$t('culture.cultureScheme.chinese')})` }}</el-button>
                    <el-button
                        @click="exportFile('pdf', 'en')"
                    >{{ $t('culture.cultureScheme.exportPdf') + ` (${$t('culture.cultureScheme.english')})` }}</el-button>
                </div>
            </div>
            <el-table
                :data="tableData"
                :cell-class-name="cellStyleMethod"
                stripe
                style="width: 100%"
                tooltip-effect="light"
                @select="selectRow"
                @selection-change="selectionChange"
            >
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <div class="edu-auto-row">
                            <div class="edu-auto-col col" style="width:100%">
                                <div class="edu-auto-label">{{ $t('culture.scheme.name') }}：</div>
                                <div class="edu-auto-content">{{ language =='en' ? props.row.nameEn :props.row.name }}</div>
                            </div>
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">{{ $t('culture.scheme.grade') }}：</div>
                                <div class="edu-auto-content">{{ props.row.grade }}</div>
                            </div>
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">{{ $t('culture.scheme.trainingLevel') }}：</div>
                                <div class="edu-auto-content">{{ props.row.trainingLevelI18n }}</div>
                            </div>
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">{{ $t('culture.scheme.faculty') }}：</div>
                                <div class="edu-auto-content">{{ props.row.facultyI18n }}</div>
                            </div>
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">{{ $t('culture.scheme.major') }}：</div>
                                <div class="edu-auto-content">
                                    <span>{{ props.row.majorI18n }}</span>
                                </div>
                            </div>
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">
                                    <el-tooltip :content="$t('culture.scheme.trainingCategory')" effect="light" placement="top">
                                        <span>
                                            {{ $t('culture.scheme.trainingCategory') }}:
                                        </span>
                                    </el-tooltip>
                                </div>
                                <div
                                    class="edu-auto-content"
                                >{{ props.row.trainingCategoryI18n }}
                                </div>
                            </div>
                            <div class="edu-auto-col col">
                                <div class="edu-auto-label">
                                    <el-tooltip :content="$t('culture.scheme.formLearning')" effect="light" placement="top">
                                        <span>
                                            {{ $t('culture.scheme.formLearning') }}:
                                        </span>
                                    </el-tooltip>
                                </div>
                                <div class="edu-auto-content">{{ props.row.formLearningI18n }}</div>
                            </div>
                            <div class="edu-auto-col col">
                                <div
                                    class="edu-auto-label"
                                >
                                    <el-tooltip :content="$t('culture.cultureScheme.cultureSchemeStatus')" effect="light" placement="top">
                                        <span>
                                            {{ $t('culture.cultureScheme.cultureSchemeStatus') }}:
                                        </span>
                                    </el-tooltip>
                                </div>
                                <div class="edu-auto-content">
                                    <el-tag
                                        type="success"
                                        size="mini"
                                        disable-transitions
                                    >{{ getPushLable(props.row.status) }}</el-tag>
                                </div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column type="selection" width="55"/>
                <el-table-column :label="$t('culture.scheme.name')" prop="name" min-width="150" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <a
                            type="text"
                            @click="preview(scope.row)"
                        >
                            {{ language =='en' ? (scope.row.nameEn || scope.row.name) :scope.row.name }}
                        </a>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('culture.scheme.grade')" prop="grade" width="80"/>
                <el-table-column :label="$t('culture.scheme.faculty')" prop="facultyI18n" width="80" show-overflow-tooltip/>
                <el-table-column :label="$t('culture.scheme.major')" prop="majorI18n" show-overflow-tooltip/>
                <el-table-column :label="$t('culture.scheme.trainingLevel')" prop="trainingLevelI18n" width="120" show-overflow-tooltip/>
                <el-table-column :label="$t('culture.scheme.trainingCategory')" prop="trainingCategoryI18n" show-overflow-tooltip width="150"/>
                <el-table-column :label="$t('dic.degreeType')" prop="degreeTypeI18n" width="120" show-overflow-tooltip/>
                <el-table-column :label="$t('culture.scheme.formLearning')" prop="formLearningI18n" width="120" show-overflow-tooltip/>
                <el-table-column :label="$t('culture.cultureScheme.cultureSchemeStatus')" width="160">
                    <template slot-scope="props">
                        <el-tag
                            type="success"
                            size="mini"
                            disable-transitions
                        >{{ getPushLable(props.row.status) }}</el-tag>
                    </template>
                </el-table-column>
            </el-table>
            <div class="edu-pagination">
                <div class="float-right">
                    <el-pagination
                        :current-page="queryForm.pageNum_"
                        :page-sizes="[20,50,100,500,1000]"
                        :page-size="queryForm.pageSize_"
                        :total="queryForm.total"
                        layout="total, sizes, prev, pager, next, jumper"
                        style="float: right;margin:0;"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </div>
            </div>
        </el-card>
    </div>
</template>
<script>
// import { judgeManagement } from './common'
// import bus from 'common/src/utils/bus'
import UTILS from 'common/src/utils/utils'
import { queryDic, findTrainingLevelByProjId, sortTrainingCategories } from 'common/src/api/dictionary'
// import { findFaculty } from 'common/src/api/faculty'
import { findDeptByCondition } from 'common/src/api/user'
import {
    findCultureSchemeListForMange,
    exportCultureSchemePdfOrWordZip,
    getCultureSchemeById,
    findProfessionByParam
} from 'common/src/api/culture/cultruescheme'
import { getPower } from 'common/src/api/culture/culturePlan'
import { getGraduateDegreePage } from 'common/src/api/resource/course'
import mixin from 'common/src/mixins/index'
export default {
    name: 'QueryCultureScheme',
    mixins: [mixin],
    data() {
        return {
            isGraduate: true,
            // 筛选相关选项
            queryForm: {
                'x-token': '',
                grade: '', // 年级
                trainingLevel: '', // 培养层次
                faculty: '', // 学院
                projId: '', //	部门管理
                professionCateGory: '', // 专业类别(1 专业大类 2 专业),
                campusProfession: '', //	本科生专业
                major: '', // 研究生专业
                type: '', // pdf或者word
                status: '3', // 状态 选项通过审批的培养方案
                formLearning: '', // 学习形式
                trainingCategory: [], // 培养类别
                name: '', // 名称
                degreeType: '', // 学位类型
                pageNum_: 1,
                pageSize_: 20,
                total: 0
            },

            // 下拉相关选项数据
            options: {
                project: [],
                trainingLevel: [],
                faculty: [],
                major: [],
                formLearning: [],
                trainingCategory: [], // 培养类别,
                professionCateGory: [
                    { value: '', label: this.$t('message.all') },
                    {
                        value: '1',
                        label: this.$t('culture.profession.bigProfession')
                    },
                    {
                        value: '2',
                        label: this.$t('culture.profession.profession')
                    }
                ],
                campusProfessions: [],
                currentRole: '',
                degreeType: []
            },
            tableData: [],
            role: '',
            showDepartment: false
        }
    },
    computed: {
        language() {
            return this.$store.getters.language
        },
        userInfo() {
            return this.$store.getters.getGlobal()
        }
    },
    created() {
        this.init()
        this.getRole()
        this.initProjId()
        this.setExportButtonVisible()
    // bus.$on("updateCurrentManageDeptId", id => {
    //     this.queryForm.projId = id;
    //     this.initTrainingLevelOptions();
    //     this.handleSearch();
    // });
    },
    methods: {
        cellStyleMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex == 2) {
                return 'normal-cell'
            }
        },
        initProjId() {
            const currentUser = this.global.currentUser
            if (currentUser.currentRole == 1) {
                // this.queryForm.projId = currentUser.currentManageDptId;
                this.queryForm.projId = '2'
                this.initTrainingLevelOptions()
                this.handleSearch()
            } else {
                this.initProjs()
            }
            this.currentRole = currentUser.currentRole
        },
        getRole() {
            getPower().then((res) => {
                this.role = res.data.power
                // if(res.data.departmentCode.indexOf(",") !=-1){
                //     let departmentCode = res.data.departmentCode.split(",")
                //     this.queryForm.faculty = departmentCode[0]
                // }else{
                //     this.queryForm.faculty = res.data.departmentCode
                // }
                // if(res.data.departmentCode && res.data.power == 3){
                //     this.queryMajors(this.queryForm.faculty)
                // }
            })
        },
        initCurrentRole() {
            const currentUser = this.global.currentUser
            this.showDepartment = currentUser.currentRole == '2' && this.options.project.length > 1
        },
        initTrainingLevelOptions() {
            findTrainingLevelByProjId(this.queryForm.projId).then(res => {
                if (res.code === 200) {
                    // this.queryForm.trainingLevel = "";
                    this.options.trainingLevel = res.data
                    this.loadTrainingLevelOptions('trainingLevel', res.data)
                }
            })
        },
        loadTrainingLevelOptions(optionKey, dataObj) {
            this.options[optionKey] = []
            this.options[optionKey] = dataObj.map(item => ({
                label:
                    this.$store.getters.language === 'en'
                        ? item.nameEN
                        : item.nameCN,
                value: item.code
            }))
        },
        setExportButtonVisible() {
            const currentUser =
                this.$store.state.session.user ||
                JSON.parse(localStorage.getItem('user'))
            this.showOperateButton = currentUser.currentRole == 1
        },
        preview(row) {
            const schemeDetails = {
                projId: row.projId,
                id: row.id,
                isRead: true,
                dataType: 2,
                templateId: row.templateId,
                nameCN: row.name,
                nameEN: row.nameEn
            }
            sessionStorage.setItem('schemeDetails', JSON.stringify(schemeDetails))
            this.$router.push({
                name: 'cultureSchemePreview',
                params: {
                    projId: row.projId,
                    id: row.id,
                    isRead: true,
                    dataType: 2,
                    templateId: row.templateId
                }
            })
        },
        init() {
            this.queryForm['x-token'] =
                this.$store.state.session.sessionid ||
                localStorage.getItem('sessionid') ||
                ''
            this.initOptions()
        },
        async initProjs() {
            const params = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: ['X_GLBM']
            }
            const res = await queryDic(params)
            // let user = this.global.currentUser;
            // let {manageDptIds} = user;
            //     manageDptIds=manageDptIds.judgeManagement(this.$router)
            // let {code, data: {X_GLBM}} = res;
            // if (code === 200) {
            //     let dpts = Object.keys(X_GLBM).map(item => ({
            //         label: X_GLBM[item],
            //         value: item + ""
            //     }))
            //     let list=judgeManagement.call(this,this.$route.path);
            //     this.options.project = dpts.filter(item => {
            //         return list.indexOf(item.value) > -1;
            //     })
            // }
            const { code, data: { X_GLBM }} = res
            if (code === 200) {
                const dpts = Object.keys(X_GLBM).map(item => ({
                    label: X_GLBM[item],
                    value: item + ''
                }))
                this.options.project = dpts.filter(item => {
                    return item.value != 1
                })
            }
            this.queryForm.projId = this.options.project[0].value
            // this.queryForm.projId = "2";
            this.initCurrentRole()
            this.initTrainingLevelOptions()
            this.handleSearch()
        },
        initOptions() {
            // findFaculty().then(res => {
            //     let data = { 'X_YX': res.data }
            //     UTILS.fillSelect({ faculty: 'X_YX' }, data, this.options)
            // })
            // 获取搜索条件中学院下拉值 所有角色都能查看所有部门的学院
            findDeptByCondition({
                isCourse:"",
                managDeptId:2
            }).then(res => {
                let xdata = { 'X_YX': res.data }
                UTILS.fillSelect({ faculty: 'X_YX' }, xdata, this.options)
            })

            const data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: ['X_PYCC', 'X_PYLB', 'K_XXXS', 'X_XWLX']
            }
            queryDic(data).then(res => {
                const params = {
                    lang: this.$store.getters.language,
                    keys: ['X_PYLB']
                }
                sortTrainingCategories(params).then((res) => {
                    this.options.trainingCategory = res.data.X_PYLB
                })
                if (res.code == 200) {
                    UTILS.fillSelect(
                        {
                            trainingLevel: 'X_PYCC',
                            formLearning: 'K_XXXS',
                            // trainingCategory: "X_PYLB",
                            degreeType: 'X_XWLX'
                        },
                        res.data,
                        this.options
                    )
                }
            })
        },
        handleSearch() {
            this.getCultureSchemes()
        },
        async getCultureSchemes() {
            await this.initTrainingLevelOptions()
            findCultureSchemeListForMange(this.queryForm).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data.list
                    this.queryForm.pageNum_ = res.data.pageNum_
                    this.queryForm.pageSize_ = res.data.pageSize_
                    this.queryForm.total = res.data.total_
                }
            })
        },
        handleSizeChange(val) {
            this.queryForm.pageSize_ = val
            this.getCultureSchemes()
        },
        handleCurrentChange(val) {
            this.queryForm.pageNum_ = val
            this.getCultureSchemes()
        },
        handSearchChang() {
            this.getCultureSchemes()
        },
        selectionChange(selection) {
            const self = this
            self.multipleSelection = selection
        },
        changeFaculty(val) {
            const self = this
            // if (self.queryForm.projId == "1") {
            //     let query = {};
            //     query.faculty = val;
            //     query.grade = +self.queryForm.grade;
            //     query.trainingLevel = self.queryForm.trainingLevel;
            //     query.category = self.queryForm.professionCateGory;
            //     self.queryCampusProfessions(query);
            // } else {
            //     if(val) {
            //         self.queryMajors();
            //     }
            // }
            if (val) {
                self.queryMajors()
            }
        },
        changeTrainingLevel(val) {
            // if (this.queryForm.projId != "1") {
            //     return;
            // }
            // const self = this;
            // let query = {};
            // query.faculty = self.queryForm.faculty;
            // query.grade = +self.queryForm.grade;
            // query.trainingLevel = val;
            // query.category = self.queryForm.professionCateGory;
            // self.queryCampusProfessions(query);
        },
        changeCategory(val) {
            const self = this
            const query = {}
            query.faculty = self.queryForm.faculty
            query.grade = +self.queryForm.grade
            query.trainingLevel = self.queryForm.trainingLevel
            query.category = val
            self.queryCampusProfessions(query)
        },
        queryMajors() {
            this.queryForm.major = ''
            this.options['major'] = []
            const data = {
                college: this.queryForm.faculty,
                type: this.queryForm.degreeType,
                page: false
            }
            getGraduateDegreePage(data).then(res => {
                if (res.code === 200) {
                    const majors = _.map(res.data.list, item => {
                        return {
                            value: item.code,
                            // label:
                            //     "cn" !== this.$store.getters.language
                            //         ? item.majorNameEn
                            //         : item.majorName
                            label:
                                    this.$store.getters.language !== 'cn'
                                        ? item.nameEn
                                        : item.name
                        }
                    })
                    majors &&
                        majors.length > 0 &&
                        (this.options['major'] = [
                            ...this.options['major'],
                            ...majors
                        ])
                }
            })
        },
        queryCampusProfessions(query) {
            // 联动校验
            if (!(query.grade && query.faculty)) {
                return
            }
            this.options.campusProfessions = []
            this.queryForm.campusProfession = ''
            findProfessionByParam(query).then(res => {
                if (res.code == 200) {
                    this.options.campusProfessions = res.data.map(
                        (item, index) => {
                            return {
                                label: item.professionCateGoryName,
                                value: item.professionCateGory
                            }
                        }
                    )
                }
            })
        },

        onSubmit() {
            this.getCultureSchemes()
        },
        reset(ref) {
            if (this.role == 3) {
                this.getRole()
                this.$refs[ref].resetFields()
                this.getCultureSchemes()
            } else {
                this.options['major'] = []
                this.$refs[ref].resetFields()
                this.getCultureSchemes()
            }
        },
        detailCultureScheme(id) {
            getCultureSchemeById(id).then(res => {
                // if (res.code == 200) {
                // }
            })
        },

        exportFile(type, language) {
            const ids = _.map(this.multipleSelection, 'id')
            if (ids.length == 0) {
                this.$message({
                    type: 'warning',
                    message: '请勾选培养方案再导出数据'
                })
                return
            }
            let projId = this.queryForm.projId
            if (!this.showDepartment) {
                projId = this.global.projectId
            }
            const str = ids.join(',')
            const data = {
                ids: str,
                type: type,
                language: language || '',
                projId,
                status: this.queryForm.status
            }
            data['x-token'] = this.queryForm['x-token']
            exportCultureSchemePdfOrWordZip(data)
        },
        getPushLable(val) {
            return val ? this.$t('culture.cultureScheme.approval') : ''
        }
    }
}
</script>
<style lang="scss" scoped>
.div-main {
    margin-bottom: 16px;
  }
</style>

